package qq2564874169.tuaotuao.fx.caching.redis;


import qq2564874169.tuaotuao.fx.caching.RemoteCache;
import qq2564874169.tuaotuao.fx.caching.RemoteCacheItem;
import qq2564874169.tuaotuao.fx.utils.IfUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisCache extends RemoteCache {
    private JedisPool pool;

    public RedisCache(JedisPool pool) {
        this.pool = pool;
    }

    @Override
    protected void saveRemote(RemoteCacheItem item) {
        String data = valueSerialize(item);
        try (Jedis jedis = pool.getResource()) {
            var expire = IfUtil.firstNotNull(item.absoluteExpiration, item.slidingExpiration);
            if (expire == null) {
                jedis.set(item.key, data);
            } else {
                jedis.setex(item.key, expire, data);
            }
        }
    }

    @Override
    protected RemoteCacheItem getRemoteItem(String key) {
        try (Jedis j = pool.getResource()) {
            String data = j.get(key);
            if (data == null) {
                return null;
            }
            var item = (RemoteCacheItem) valueDeserialize(data, RemoteCacheItem.class);
            if (item.slidingExpiration != null) {
                j.expire(key, item.slidingExpiration);
            }
            return item;
        }
    }

    @Override
    protected void deleteRemote(String key) {
        try (Jedis j = pool.getResource()) {
            j.del(key);
        }
    }

    @Override
    protected boolean existsRemote(String key) {
        try (Jedis j = pool.getResource()) {
            return j.exists(key);
        }
    }
}
